package h0827;

import java.util.*;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 合并区间
 * @date 2024/8/27 18:24
 */
public class MrgeInterval {
    public static void main(String[] args) {
        int[][] intervals = new int[][]{{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        int[][] merge = merge(intervals);
        for (int[] interval : merge) {
            System.out.println(Arrays.toString(interval));
        }
    }

    public static int[][] merge(int[][] intervals) {
        //a按照起始时间排序
        Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]);
        int start = intervals[0][0];
        int end = intervals[0][1];
        List<int[]> ans = new ArrayList<>();
        for (int i = 1; i < intervals.length; i++) {
            if (end < intervals[i][0]) {
                ans.add(new int[]{start, end});
                start = intervals[i][0];
                end = intervals[i][1];
            }else if (intervals[i][1]>end){
                end=intervals[i][1];
            }
        }
        //还有最后
        ans.add(new int[]{start,end});
        int[][] res = new int[ans.size()][];
        for (int i = 0; i < res.length; i++) {
            res[i]=ans.get(i);
        }
        return res;
    }
}
